package com.yq.ylmall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.ylmall.constant.ProductConstant;
import com.yq.ylmall.model.product.Banner;
import com.yq.ylmall.product.mapper.BannerMapper;
import com.yq.ylmall.product.service.IBannerService;
import com.yq.ylmall.service.CacheService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yzk789
 * @since 2024-06-17
 */
@Service
@RequiredArgsConstructor
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements IBannerService {

    private final CacheService cacheService;

    @Override
    public String findAll() {
        // 查询缓存
        String cache = cacheService.get(ProductConstant.BANNER_CACHE);
        if (StrUtil.isNotBlank(cache)) return cache;
        if (cache != null) return null;
        // 未命中缓存，访问数据库
        List<Banner> bannerList = baseMapper.selectList(
                Wrappers.<Banner>lambdaQuery()
                        .eq(Banner::getStatus, 1)
                        .orderByDesc(Banner::getSort)
        );
        if (bannerList.isEmpty()) {
            cacheService.set(ProductConstant.BANNER_CACHE, "");
            return null;
        }
        String result = JSON.toJSONString(bannerList);
        cacheService.set(ProductConstant.BANNER_CACHE, result);
        return result;
    }

}
